//
//  WSJHorTableView.m
//  滚动的任意添加的图
//
//  Created by wsj2015 on 16/2/23.
//  Copyright © 2016年 wsj2015. All rights reserved.
//

#import "WSJHorTableView.h"
#import "WCNPiccell.h"
#import "JKImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "WCImageView +setImage.h"
#import "WCImageManager.h"
#import "JCAlertView.h"


#import "LGPhotoPickerViewController.h"
#import "LGPhotoAssets.h"



@interface WSJHorTableView ()<UITableViewDelegate,UITableViewDataSource,LGPhotoPickerViewControllerDelegate>

@property (nonatomic,  strong) UITableView *tableView;

@property (nonatomic,  strong) NSMutableArray<LGPhotoAssets *> *lastSelectMoldels;


@end

@implementation WSJHorTableView
- (NSMutableArray *)dateArray{
    if (!_dateArray) {
        _dateArray =[NSMutableArray array];
    }
    return _dateArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width,60) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource =self;
        _tableView.showsVerticalScrollIndicator = NO;
    
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
    }

    return _tableView;
}
//
- (NSArray *)currentPics{
    //
 
    NSMutableArray *array =[NSMutableArray arrayWithArray:self.dateArray];
    if (array.count>=1) {
          [array removeObjectAtIndex:0];
    }
    NSMutableArray *bigArr =[NSMutableArray array];
    for (WSJImage *model in array) {
        
        [bigArr addObject:model.bigImage];
    }
   return bigArr;

}

- (void)setType:(WSJHorTableViewType)type{
    _type = type;
    if (type == WSJHorTableViewTypeEdite) {
        [self resetDateArray];
    }

}
-  (void)resetDateArray{
    [self.dateArray removeAllObjects];
    WSJImage *image =[WSJImage new];
    image.bigImage =[UIImage imageNamed:@"Image_add"];
    [self.dateArray insertObject:image atIndex:0];
}
- (NSMutableArray<LGPhotoAssets *> *)lastSelectMoldels{
    if (!_lastSelectMoldels) {
        _lastSelectMoldels =[NSMutableArray array];
    }
    return _lastSelectMoldels;
}
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        
        
        [self addSubview:self.tableView];
        _maxImageCount = 100;
        
        CGFloat l =frame.size.width/2;
        CGFloat  h = frame.size.height;
        self.tableView.frame =CGRectMake(l - h/2, -( l)/2-h+17, h, frame.size.width);
        self.tableView.transform  =CGAffineTransformRotate(self.tableView.transform, -M_PI / 2);
        
//        self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 40, 0);
        [self.tableView registerNib:[UINib nibWithNibName:@"WCNPiccell" bundle:nil] forCellReuseIdentifier:@"WCNPiccellId"];
       
        
    }
    return self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.type ==0) {
        return self.dateArray.count;
    }else{
        return self.imageUrls.count;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.frame.size.height +10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WCNPiccell *cell =[tableView dequeueReusableCellWithIdentifier:@"WCNPiccellId" forIndexPath:indexPath];
   
    if (self.type ==0) {
      
     cell.delBtn.hidden =indexPath.row==0?YES:NO;
        WSJImage *image = self.dateArray[indexPath.row];
     cell.pic.image = image.thumbImage;
        __weak typeof(self) weakself = self;
        cell.delAction = ^(UIImage *thumbimage){
            NSInteger index = indexPath.row;
            [weakself.dateArray removeObjectAtIndex:index];
            [weakself.lastSelectMoldels removeObjectAtIndex:index-1];
            [weakself.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationRight];
            [weakself.tableView reloadData];
        };
       
    }else{
        cell.delBtn.hidden = YES;
        cell.imageUrl = self.imageUrls[indexPath.row];
        cell.vcDelegate=^(){return self.presentDelegate();};
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.type == WSJHorTableViewTypeEdite) {
        if (indexPath.row ==0) {
            [self pickPics];
        }
    }else{
       
    }
    
    
}
 -(void)pickPics
{
    
    LGPhotoPickerViewController *pickerVc = [[LGPhotoPickerViewController alloc] initWithShowType:0];
    pickerVc.status = PickerViewShowStatusCameraRoll;
    pickerVc.maxCount = 9;   // 最多能选9张图片
    pickerVc.delegate = self;
    pickerVc.selectPickers = self.lastSelectMoldels;
    [pickerVc showPickerVc:self.presentDelegate()];
//    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
//    //设置照片最大选择数
//    actionSheet.maxSelectCount = 9;
//    //设置照片最大预览数
//    actionSheet.maxPreviewCount = 20;
//    defineWeakSelf;
//    [actionSheet showWithSender:self.presentDelegate() animate:YES lastSelectPhotoModels:self.lastSelectMoldels completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
//       
//        [weakSelf resetDateArray];
//        for (UIImage *img in selectPhotos) {
//            WSJImage *image =[WSJImage new];
//            image.bigImage =[UIImage imageWithData:UIImageJPEGRepresentation(img, 0.5)];
//            
//            [weakSelf.dateArray addObject:image];
//        }
//        
//        weakSelf.lastSelectMoldels = [selectPhotoModels mutableCopy];
//        [weakSelf.tableView reloadData];
//        NSLog(@"%@", selectPhotos);
//    }];

    
    
    
    
//    JKImagePickerController *imagePickerController = [[JKImagePickerController alloc] init];
//    imagePickerController.delegate = self;
//    imagePickerController.showsCancelButton = YES;
//    imagePickerController.allowsMultipleSelection = YES;
//    imagePickerController.minimumNumberOfSelection = 1;
//    imagePickerController.maximumNumberOfSelection = 9;
////    imagePickerController.selectedAssetArray = self.assetsArray;
//    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
//    [self.presentDelegate() presentViewController:navigationController animated:YES completion:NULL];


}
#pragma mark - LGPhotoPickerViewControllerDelegate

- (void)pickerViewControllerDoneAsstes:(NSArray *)assets isOriginal:(BOOL)original{
    /*
     //assets的元素是LGPhotoAssets对象，获取image方法如下:
     NSMutableArray *thumbImageArray = [NSMutableArray array];
     NSMutableArray *originImage = [NSMutableArray array];
     NSMutableArray *fullResolutionImage = [NSMutableArray array];
     
     for (LGPhotoAssets *photo in assets) {
     //缩略图
     [thumbImageArray addObject:photo.thumbImage];
     //原图
     [originImage addObject:photo.originImage];
     //全屏图
     [fullResolutionImage addObject:fullResolutionImage];
     }
     */
    

//    
//    NSInteger num = (long)assets.count;
//    NSString *isOriginal = original? @"YES":@"NO";
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"发送图片" message:[NSString stringWithFormat:@"您选择了%ld张图片\n是否原图：%@",(long)num,isOriginal] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//    [alertView show];
  
#if DEBUG
//    CGFloat f = 0;
//    for (LGPhotoAssets *set in assets) {
//        WSJImage *image =[WSJImage new];
//        image.bigImage  =set.compressionImage;
//        
//        f += UIImageJPEGRepresentation(set.compressionImage, 1).length/1024;
//        
//    }
//        NSInteger num = (long)assets.count;
////        NSString *isOriginal = original? @"YES":@"NO";
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"发送图片" message:[NSString stringWithFormat:@"您选择了%ld张图片\n总大小：%.2fKB",(long)num,f] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alertView show];

    
#else
    

#endif
    
    [self resetDateArray];
    for (LGPhotoAssets *set in assets) {
        WSJImage *image =[WSJImage new];
        image.bigImage  =set.compressionImage;
        
        [self.dateArray addObject:image];
    }

    self.lastSelectMoldels = assets;
    [self.tableView reloadData];
    

}
#pragma mark - JKImagePickerControllerDelegate
//- (void)imagePickerController:(JKImagePickerController *)imagePicker didSelectAsset:(JKAssets *)asset isSource:(BOOL)source
//{
//    [imagePicker dismissViewControllerAnimated:YES completion:^{
//        
//    }];
//}
//
//- (void)imagePickerController:(JKImagePickerController *)imagePicker didSelectAssets:(NSArray *)assets isSource:(BOOL)source
//{
////    self.assetsArray = [NSMutableArray arrayWithArray:assets];
//    
//    ALAssetsLibrary   *lib = [[ALAssetsLibrary alloc] init];
//    defineWeakSelf;
//    if (assets.count>0) {
//        for (JKAssets *set in assets) {
//            [lib assetForURL:set.assetPropertyURL resultBlock:^(ALAsset *asset) {
//                if (asset) {
//                    if (weakSelf.dateArray.count < self.maxImageCount + 1) {
//                        WSJImage *image =[WSJImage new];
//                        image.bigImage =[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
//                       [weakSelf.dateArray addObject:image];
//                        [weakSelf.tableView reloadData];
//                        
//                    }
//                }
//            } failureBlock:^(NSError *error) {
//                
//            }];
//        }
//    }
// 
//    
////    [self.dateArray addObjectsFromArray:assets];
//    [imagePicker dismissViewControllerAnimated:YES completion:^{
//        [self.tableView reloadData];
//    }];
//}
//
//- (void)imagePickerControllerDidCancel:(JKImagePickerController *)imagePicker
//{
//    [imagePicker dismissViewControllerAnimated:YES completion:^{
//        
//    }];
//}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
  

}

#pragma mark - 上传图片
- (void)startUploadImages
{
    NSArray *selImages = self.currentPics;
    if (selImages.count == 0) {
        
        self.blockBackImageNames(nil);
        return;
    }

    __block NSArray *temArray;
    __block NSInteger isFailue = 0;;
    defineWeakSelf;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        temArray = selImages;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *message;
            if (_maxImageCount < 9) {
                message = [NSString stringWithFormat:@"是否确认上传图片,请一次上传不要超过%d张",_maxImageCount];
            }else {
               message = @"是否确认上传图片,请一次上传不要超过8张";
                           
            }
            [JCAlertView showTwoButtonsWithTitle:@"提示" Message:message ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"否" Click:^{
                
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确认" Click:^{
                //上传图片
                
                __block CGFloat progress =0;
                
                [CoreSVP showProgess:progress Msg:@"上传进度..." maskType:SVProgressHUDMaskTypeClear];
                
                //------------------------------------
                __block NSInteger sucessTag = 0;
                NSMutableArray *namesArray =[NSMutableArray array];
                for (int i =0; i<temArray.count; i++) {
                    [[WCImageManager sharedMg] uploadImage:@[temArray[i]] multi:NO progress:^(NSProgress *progress) {
                        
                       
                        
                        
                    } success:^(NSDictionary *result){
                        //                    [hud hide:YES];
                        sucessTag ++;
                        CGFloat  progress = (CGFloat)sucessTag /(CGFloat)temArray.count;
                        [CoreSVP showProgess:progress Msg:@"上传进度..." maskType:SVProgressHUDMaskTypeClear];
                        NSString * imageId =result[@"data"][@"name"];
                        if (imageId) {
                            [namesArray addObject:imageId];
                        }
                        
                        if (sucessTag ==temArray.count) {
                            weakSelf.blockBackImageNames(namesArray);
                        }
                        
                    } failure:^(NSString *msg){
                        
                        if (isFailue==0) {
                            isFailue =1;
                            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"上传失败" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"知道了" Click:nil];
                        }
                        
                        [CoreSVP dismiss];
                        
                    }];
                    
                }
                
            }];
            
        });
        
    });
}

- (void)dealloc{
    
    self.currentPics = nil;
    self.lastSelectMoldels = nil;
    self.tableView = nil;
    NSLog(@"WSJHorTalbeView 被释放了");

}






@end
